package com.iot.relay;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.iot.constants.CallStatusEnum;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

/**
 * @author RodulphLiu
 * @version 1.0.0
 * @ClassName ExchangeData
 * @Date 2017年3月31日 下午4:53:42
 */
@Data
@Slf4j
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ExchangeData<T> {
    /**
     * 需要返回id情况下使用
     */
    @ApiModelProperty(value = "ID")
    private Long id;

    /**
     * 提示信息,前端/调用方直接显示
     */
    @ApiModelProperty(value = "提示信息")
    private String message = "";

    @SuppressWarnings("unchecked")
    @ApiModelProperty(value = "数据内容")
    private T data = (T) new String[]{};

    @ApiModelProperty(value = "请求状态")
    private CallStatusEnum callStatus = CallStatusEnum.SUCCESS;

    @ApiModelProperty(value = "响应结果状态")
    private HttpStatus status;

    /**
     * 返回成功
     *
     * @param message
     */
    public void markSuccess(String message) {
        callStatus = CallStatusEnum.SUCCESS;
        status = HttpStatus.OK;
        this.message = message;
    }

    /**
     * 返回失败
     */
    public void markFail() {
        callStatus = CallStatusEnum.FAIL;
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        this.message = "系统异常,请稍后再试";
    }

    /**
     * 返回失败带提示语
     *
     * @param message 提示语
     */
    public void markFail(String message) {
        callStatus = CallStatusEnum.FAIL;
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        if (StrUtil.isNotBlank(message)) {
            this.message = message;
        } else {
            markFail();
        }
    }

    /**
     * 返回异常
     *
     * @param e
     */
    public void markException(Exception e) {
        callStatus = CallStatusEnum.FAIL;
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        this.message = e.getMessage();
        log.error(e.getMessage(), e);
    }

    /**
     * 返回异常带提示语
     *
     * @param message
     * @param e
     */
    public void markException(String message, Exception e) {
        callStatus = CallStatusEnum.FAIL;
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        this.message = message;
        log.error(e.getMessage(), e);
    }
}
